/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OldVisits.java
 *
 * Created on Sep 3, 2009, 8:48:04 PM
 */

package GUI;

import functions.Dogy;
import functions.HealingSet;
import functions.ItemList;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;
import model.Diagnose;
import model.Item;
import functions.OldUsers;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.KeyStroke;
import model.User;
import model.Visit;

/**
 *
 * @author JArik
 */
public class OldVisits extends javax.swing.JFrame {

    /** Creates new form OldVisits */
    private MainFrame mainFrame;
    private User user;
    private UserCard userCard;
    public OldVisits() {
        initComponents();
    }
    public OldVisits(MainFrame mf, User u, UserCard card)
    {
        mainFrame = mf;
        user = u;
        userCard = card;
        this.setTitle("Старые визиты - "+ u.getFullName());
        initComponents();
        fillVisits();
    }
    private void fillVisits()
    {
        try
        {
           HealingSet healing = OldUsers.getOldVisits(user.getId());
           DefaultTableModel model = (DefaultTableModel)healingTable.getModel();
           for(int i=0; i < healing.size(); i++)
           {
               if(healing.getVisit(i) instanceof ItemList)
                 for(int l=0; l< healing.getVisit(i).size(); l++)
                     if(healing.getVisit(i).get(l) instanceof Visit)
                     {
                            model.addRow(new Object[] { healing.getVisit(i),
                            ((Visit)healing.getVisit(i).get(l)).getStatus(),
                            healing.getResult() });
                            break;
                     }
           }
           if(healing.size() > 0 )
           {
               healingTable.setRowSelectionInterval(0, 0);
               healingTableMouseReleased(null);
           }
           healingTable.setModel(model);
        } catch(SQLException e)
        {
            mainFrame.SQLException(e);
        }

        KeyStroke kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W,2);
        InputMap map = healingTable.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "ctrlW");
        ActionMap actionMap = healingTable.getActionMap();
        actionMap.put("ctrlW", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        ((javax.swing.JFrame)healingTable.getRootPane().getParent()).dispose();
                     }
             });
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        closeButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        itemTable = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        diagTable = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        finTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        doctorNameField = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        descrField = new javax.swing.JTextArea();
        jScrollPane6 = new javax.swing.JScrollPane();
        healingTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(null);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        closeButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        itemTable.setAutoCreateRowSorter(true);
        itemTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        itemTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Название", "Кол-во"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        itemTable.setRowHeight(20);
        jScrollPane2.setViewportView(itemTable);
        itemTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        itemTable.getColumnModel().getColumn(1).setHeaderValue("Кол-во");

        jTabbedPane1.addTab("Прием", jScrollPane2);

        diagTable.setAutoCreateRowSorter(true);
        diagTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        diagTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Название", "Окончательный"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        diagTable.setRowHeight(20);
        jScrollPane4.setViewportView(diagTable);
        diagTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        diagTable.getColumnModel().getColumn(1).setMaxWidth(150);

        jTabbedPane1.addTab("Диагнозы", jScrollPane4);

        finTable.setAutoCreateRowSorter(true);
        finTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        finTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Название", "Сумма"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        finTable.setRowHeight(20);
        jScrollPane3.setViewportView(finTable);
        finTable.getColumnModel().getColumn(0).setPreferredWidth(180);

        jTabbedPane1.addTab("Фин. Отчет", jScrollPane3);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Врач:");

        doctorNameField.setFont(new java.awt.Font("Tahoma", 0, 12));

        descrField.setColumns(20);
        descrField.setEditable(false);
        descrField.setFont(new java.awt.Font("Tahoma", 0, 12));
        descrField.setLineWrap(true);
        descrField.setRows(5);
        jScrollPane5.setViewportView(descrField);

        healingTable.setAutoCreateRowSorter(true);
        healingTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        healingTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Дата", "Состояние", "Результат"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        healingTable.setRowHeight(20);
        healingTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                healingTableMouseReleased(evt);
            }
        });
        healingTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                healingTableKeyReleased(evt);
            }
        });
        jScrollPane6.setViewportView(healingTable);
        healingTable.getColumnModel().getColumn(0).setPreferredWidth(150);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(closeButton)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(doctorNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
                    .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(doctorNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void healingTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_healingTableMouseReleased
        DefaultTableModel healModel = (DefaultTableModel)healingTable.getModel();
        DefaultTableModel itemModel = (DefaultTableModel)itemTable.getModel();
        DefaultTableModel finModel = (DefaultTableModel)finTable.getModel();
        DefaultTableModel diagModel = (DefaultTableModel)diagTable.getModel();
        itemModel.setRowCount(0);
        finModel.setRowCount(0);
        diagModel.setRowCount(0);
        double total=0;
        if(healingTable.getSelectedRow() == -1)
            return;
        ItemList visitDetails = (ItemList)healModel.getValueAt(healingTable.getSelectedRow(), 0);
        
        for(int i =0; i< visitDetails.size(); i++)
        {
            if(visitDetails.get(i) instanceof Visit)
            {
                Visit visit = (Visit)visitDetails.get(i);
                doctorNameField.setText(visit.getDoctor().getFullName());
                descrField.setText(""+visit.getDescr());
                if(visit.getRecom() != null && !visit.getRecom().isEmpty())
                      descrField.setText(descrField.getText()+
                                         "\nРекомендации:\n" +
                                          visit.getRecom());
                
                finModel.addRow(new Object[]{"Визит",visit.getPayed()});
                finModel.addRow(new Object[]{"Другое",visit.getVisitOtherPayed()});
                total +=visit.getPayed() + visit.getVisitOtherPayed();
            }else
            if(visitDetails.get(i) instanceof Diagnose)
            {
                Diagnose diag = (Diagnose)visitDetails.get(i);
                diagModel.addRow(new Object[]{diag, !diag.isPredv()});
            }else
            if(visitDetails.get(i) instanceof Item)
            {
                Item item = (Item)visitDetails.get(i);
                itemModel.addRow(new Object[]{item, item.getAmount()});
                finModel.addRow(new Object[]{item,item.getPayed()});
                total +=item.getPayed();
            }

         }
            itemTable.setModel(itemModel);
            finModel.addRow(new Object[]{"<html><b>Итого</b>","<html><b>"+total+"</b>"});
            finTable.setModel(finModel);
            diagTable.setModel(diagModel);
    }//GEN-LAST:event_healingTableMouseReleased

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        Dogy.placeToCenter(userCard);
        userCard.setOldVisitsVisible(false);
        
    }//GEN-LAST:event_formWindowClosing

    private void healingTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_healingTableKeyReleased
        healingTableMouseReleased(null);
    }//GEN-LAST:event_healingTableKeyReleased

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        userCard.setOldVisitsVisible(false);
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OldVisits().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JTextArea descrField;
    private javax.swing.JTable diagTable;
    private javax.swing.JLabel doctorNameField;
    private javax.swing.JTable finTable;
    private javax.swing.JTable healingTable;
    private javax.swing.JTable itemTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables

}
